/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.HandlingService;
import com.jeeplus.modules.infor.service.LoadDetilService;
import com.jeeplus.modules.infor.service.LoadjsDetilService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.service.LoadJsService;

/**
 * 装卸结算单Controller
 * @author 李超辉
 * @version 2018-09-29
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/loadJs")
public class LoadJsController extends BaseController {

	@Autowired
	private LoadJsService loadJsService;
	@Autowired
	private LoadDetilService loadDetilService;
	@Autowired
	private LoadjsDetilService loadjsDetilService;
	@Autowired
	private HandlingService handlingService;

	
	@ModelAttribute
	public LoadJs get(@RequestParam(required=false) String id) {
		LoadJs entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = loadJsService.get(id);
		}
		if (entity == null){
			entity = new LoadJs();
		}
		return entity;
	}
	
	/**
	 * 装卸结算单列表页面
	 */
	@RequiresPermissions("infor:loadJs:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/loadJsList";
	}
	/**
	 * 装卸结算单列表页面
	 */
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/infor/4/loadJsList";
	}
	
		/**
	 * 装卸结算单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadJs:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(LoadJs loadJs, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LoadJs> page = loadJsService.findPage(new Page<LoadJs>(request, response), loadJs); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑装卸结算单表单页面
	 */
	@RequiresPermissions(value={"infor:loadJs:view","infor:loadJs:add","infor:loadJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LoadJs loadJs, Model model) {
		model.addAttribute("loadJs", loadJs);
		LoadjsDetil rent=new LoadjsDetil();
		rent.setPid(loadJs.getId());
		List<LoadjsDetil> lisyt=loadjsDetilService.findList(rent);
		model.addAttribute("list",lisyt);
		return "modules/infor/loadJsForm";
	}

	/**
	 * 开票
	 */@RequestMapping(value = "form1")
	public String form1(LoadJs loadJs,String je,String i, Model model) {
		loadJs.setDate(new Date());
		if(!UserUtils.getUseroffice().equals("总部")){
			loadJs.setPro(UserUtils.getUseroffice());
		}
		loadJs.setStatus("已创建");
		loadJs.setTid(i);
		loadJs.setKpje(je);
		loadJs.setHx("0");
		loadJs.setWhx(je);
		model.addAttribute("loadJs", loadJs);
		return "modules/infor/3/loadJsForm";
	}
	/**
	 * 取消开票
	 */
	@ResponseBody
	@RequestMapping(value = "qxkp")
	public AjaxJson qxkp(LoadJs loadJs, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String i=loadJs.getTid();
		String[] ids=i.split(",");
		for(String id:ids){
			Handling h=handlingService.get(id);
			h.setKpzt("未开票");
			handlingService.save(h);
		}
		loadJsService.delete(loadJs);
		j.setMsg("取消开票成功");
		return j;
	}

	/**
	 * 核销
	 */
	@ResponseBody
	@RequestMapping(value = "qxhx")
	public AjaxJson qxhx(LoadJs loadJs) {
		AjaxJson j = new AjaxJson();
		loadJs.setWhx(loadJs.getKpje());
		loadJs.setHx("0");
		loadJs.setStatus("已创建");
		loadJsService.save(loadJs);
		LoadjsDetil rent=new LoadjsDetil();
		rent.setPid(loadJs.getId());
		List<LoadjsDetil> lisyt=loadjsDetilService.findList(rent);
		for(LoadjsDetil l:lisyt){
			loadjsDetilService.delete(l);
		}
		j.setMsg("取消核销成功");
		return j;
	}
	/**
	 * 关账
	 */
	@ResponseBody
	@RequestMapping(value = "gz")
	public AjaxJson gz(LoadJs loadJs) {
		AjaxJson j = new AjaxJson();
		loadJs.setStatus("已关账");
		loadJsService.save(loadJs);
		j.setMsg("关账成功");
		return j;
	}
	/**
	 * 核销
	 */
	@ResponseBody
	@RequestMapping(value = "hx")
	public AjaxJson hx(LoadJs loadJs,String je,String person,Date date,String type,String fee,String remarks) {
		AjaxJson j = new AjaxJson();
		LoadjsDetil detil=new LoadjsDetil();
		detil.setPid(loadJs.getId());
		detil.setDate(date);
		detil.setPerson(person);
		detil.setFee(fee);
		detil.setMoney(je);
		detil.setType(type);
		detil.setRemarks(remarks);
		loadjsDetilService.save(detil);
		String ids=loadJs.getTid();
		String kpje=loadJs.getKpje();
		String[] idd=ids.split(",");
		for(String id:idd){
			Handling sb=handlingService.get(id);
			String kp=sb.getKpje();
			String dz=sb.getDzje();
			double dzje=Double.parseDouble(je)/Double.parseDouble(kpje)*Double.parseDouble(kp);
			double ndz=Double.parseDouble(dz)+dzje;
			sb.setDzje(ndz+"");
			handlingService.save(sb);
		}
		double hxje=Double.parseDouble(je)+Double.parseDouble(loadJs.getHx());
		double whx=Double.parseDouble(loadJs.getWhx())-Double.parseDouble(je);
		NumberFormat nf = NumberFormat.getInstance();
		loadJs.setWhx(nf.format(whx).replaceAll(",",""));
		loadJs.setHx(nf.format(hxje).replaceAll(",",""));
		if(Double.parseDouble(loadJs.getKpje())==hxje){
			loadJs.setStatus("已核销");
		}else{
			loadJs.setStatus("部分核销");
		}
		loadJsService.save(loadJs);
		j.setMsg("核销成功");
		return j;
	}
	/**
	 * 保存装卸结算单
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:loadJs:add","infor:loadJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(LoadJs loadJs, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, loadJs)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(loadJs.getIsNewRecord()){
			String i=loadJs.getTid();
			String[] ids=i.split(",");
			for(String id:ids){
				Handling h=handlingService.get(id);
				h.setKpzt("已开票");
				h.setKpje(h.getZsr());
				h.setKprq(loadJs.getDate());
				h.setFph(loadJs.getFph());
				h.setDzje("0");
				handlingService.save(h);
			}
		}
		loadJsService.save(loadJs);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存装卸结算单成功");
		return j;
	}
	
	/**
	 * 删除装卸结算单
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadJs:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(LoadJs loadJs, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		loadJsService.delete(loadJs);
		j.setMsg("删除装卸结算单成功");
		return j;
	}
	
	/**
	 * 批量删除装卸结算单
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadJs:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			loadJsService.delete(loadJsService.get(id));
		}
		j.setMsg("删除装卸结算单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadJs:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(LoadJs loadJs, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "装卸结算单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LoadJs> page = loadJsService.findPage(new Page<LoadJs>(request, response, -1), loadJs);
    		new ExportExcel("装卸结算单", LoadJs.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出装卸结算单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:loadJs:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LoadJs> list = ei.getDataList(LoadJs.class);
			for (LoadJs loadJs : list){
				try{
					loadJsService.save(loadJs);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条装卸结算单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条装卸结算单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入装卸结算单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loadJs/?repage";
    }
	
	/**
	 * 下载导入装卸结算单数据模板
	 */
	@RequiresPermissions("infor:loadJs:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "装卸结算单数据导入模板.xlsx";
    		List<LoadJs> list = Lists.newArrayList(); 
    		new ExportExcel("装卸结算单数据", LoadJs.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loadJs/?repage";
    }

}